import os
import re
from datetime import datetime

OUTPUT_FILE = "code_lines_count_output.txt"
GREEN = '\033[92m'  
BLUE = '\033[94m'   
RESET = '\033[0m'   

timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

results = []
total = 0

def should_exclude(file_path):
    file_name = os.path.basename(file_path)
    if os.path.dirname(file_path).endswith('..'):
        if file_name.endswith(('.h', '.cpp')):
            return True
    return False

for root, dirs, files in os.walk('..'):
    if 'assets' in dirs:
        dirs.remove('assets')  
    
    for file_name in files:
        file_path = os.path.join(root, file_name)
        
        if should_exclude(file_path):
            continue
        
        if file_name.endswith(('.cpp', '.h', '.c', '.hpp', '.ino')):
            try:
                with open(file_path, 'r', encoding='utf-8', errors='ignore') as file:
                    count = sum(1 for line in file if re.search(r'\S', line))
                    results.append(f"{GREEN}{count:6d}{RESET} {file_path}\n")
                    total += count
            except Exception as e:
                results.append(f"{RED}Error reading {file_path}: {e}{RESET}\n")

output_content = []
output_content.append('\n')
output_content.append("="*100)
output_content.append('\n')
output_content.append(f"Timestamp {BLUE}{timestamp}{RESET}\n")
output_content.append("-"*100)
output_content.append('\n')
output_content.extend(results)
output_content.append("-"*100)
output_content.append(f"\n{GREEN}{total:6d}{RESET} Total\n")
output_content.append("="*100)
output_content.append("\n\n")

with open(OUTPUT_FILE, 'a') as f:
    f.writelines(output_content)
